package com.ycsj.goldmedalnewconcept.fragment;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.activity.AnswerListDetailsActivity;
import com.ycsj.goldmedalnewconcept.activity.FollowReadDetailsActivity;
import com.ycsj.goldmedalnewconcept.activity.GrammarThirdActivity;
import com.ycsj.goldmedalnewconcept.activity.LoginActivity;
import com.ycsj.goldmedalnewconcept.bean.GrammarSecondListInfo;
import com.ycsj.goldmedalnewconcept.bean.GrammarSecondResp;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.view.FerrisWheelLayout;
import com.ycsj.goldmedalnewconcept.R;

/**
 * 首页fragment ViewPager tab
 * 
 * @author dewyze 语法轮循球
 */
public class GrammarSecondFragment extends BaseFragment {

	private static final String TAG = "GrammarSecondFragment";
	private Activity mActivity;
	private TextView mMsgTv;
	private String mMsgName;
	private TextView tv_title;
	private RelativeLayout progressBar;
	private ImageView iv_person;
	// 用于区分是否是跟读界面跳转过来的界面
	private String type;

	public void setMsgName(String msgName) {
		this.mMsgName = msgName;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.mActivity = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_miniclass_second,
				container, false);
		int GRADE_ID = getArguments().getInt("GRADE_ID");
		progressBar = (RelativeLayout) view.findViewById(R.id.progressBar);
		fwl = (FerrisWheelLayout) view.findViewById(R.id.fw_fwl);
		iv_person = (ImageView) view.findViewById(R.id.iv_person);
		fwl.setFirstNum(SPUtils.getInt(getActivity(), "firstNum"));

		// 获取是否是从跟读界面跳转过来的标记
		type = getArguments().getString("type");

		Log.i("test", "获取到的type的值是 :" + type);
		if(TextUtils.isEmpty(type) || !type.equals("FOLLOWREAD")){
			
		}else{
			
			iv_person.setBackgroundResource(R.drawable.cover_people4);
			
		}
		
		
		
		final Handler handler = new Handler();

		// 创建okHttpClient对象
		OkHttpClient mOkHttpClient = new OkHttpClient();
		// 创建一个Request
		final Request request = new Request.Builder().url(
				NetConstant.ycsj_platform
						+ "?type=6&gradeid="
						+ GRADE_ID
						+ "&account="
						+ SPUtils.getString(getActivity(),
								ConfigConstant.USERNAME) + "&role="
						+ SPUtil.getString(getActivity(), "role", "0")).build();
		// new call
		Call call = mOkHttpClient.newCall(request);

		// 请求加入调度
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Request request, IOException e) {
			}

			@Override
			public void onResponse(Response response) throws IOException {

				String json = response.body().string();
				// 使用Gson把json解析成对象
				// 1 得到gson对象
				Log.e("test", json);
				Gson gson = new Gson();
				// // 2 使用gson对象的方法
				GrammarSecondResp grammarSecondResp = gson.fromJson(json,
						GrammarSecondResp.class);
				list.addAll(grammarSecondResp.LIST);
				if (list.size() == 18) {
					SPUtils.put(getActivity(), "UnitCount", 18);
				} else {
					SPUtils.put(getActivity(), "UnitCount", 4);
				}

				
				
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						if (!SPUtils.getBoolean(getActivity(),
								ConfigConstant.IS_LOGIN_ON)) {

							fwl.setcount(4);
							progressBar.setVisibility(progressBar.GONE);
							fwl.setVisibility(View.VISIBLE);
							for (int i = 8; i > 3; i--) {
								fwl.getChildAt(i).setVisibility(View.GONE);
							}

						} else {
							fwl.setcount(SPUtils.getInt(getActivity(),
									"UnitCount"));
							progressBar.setVisibility(progressBar.GONE);
							fwl.setVisibility(View.VISIBLE);
							Log.e("LoginActivity",
									"ccccc"
											+ SPUtils.getInt(getActivity(),
													"UnitCount"));
							for (int i = 8; i >= SPUtils.getInt(getActivity(),
									"UnitCount"); i--) {
								fwl.getChildAt(i).setVisibility(View.GONE);

							}
						}
					}
				}, 2000);

				int childCount = fwl.getChildCount();
				for (int i = 0; i < childCount; i++) {
					fwl.getChildAt(i).setOnClickListener(toastTagOcl);
				}

			}
		});

		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initViews(view);

		SPUtils.put(getActivity(), ConfigConstant.CURRENTFRAGMENT, TAG);
		String GRADE_NAME = getArguments().getString("GRADE_NAME");
		tv_title.setText(GRADE_NAME);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	private void initViews(View view) {
		tv_title = (TextView) view.findViewById(R.id.tv_title);
		TextView tv_back = (TextView) view.findViewById(R.id.tv_back);
		tv_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				HomeFragment gf = new HomeFragment();
				ft.replace(R.id.center_layout, gf);
				ft.addToBackStack(null);
				ft.commit();
			}
		});
	}

	@Override
	public String getFragmentName() {
		return TAG;
	}

	public OnTouchListener onTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:

				break;
			case MotionEvent.ACTION_UP:

				Animation shakeAnim = AnimationUtils.loadAnimation(
						getActivity(), R.anim.shake);
				v.startAnimation(shakeAnim);

				break;
			}
			return true;
		}

	};

	private FerrisWheelLayout fwl;

	public Animation shakeAnimation(int CycleTimes) {
		Animation translateAnimation = new TranslateAnimation(0, 0, -10, 10);
		translateAnimation.setInterpolator(new CycleInterpolator(CycleTimes));
		translateAnimation.setDuration(1000);
		return translateAnimation;
	}

	// 轮询球的点击事件
	private OnClickListener toastTagOcl = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// 没有登录,跳转到登录界面
//			if (!SPUtils.getBoolean(getActivity(), ConfigConstant.IS_LOGIN_ON)) {
//				Intent intent = new Intent(getActivity(), LoginActivity.class);
//				startActivity(intent);
//			} else {
				// 登录以后
				TextView tv = (TextView) v;
				final int index = Integer.parseInt((String) tv.getText()
						.toString())
						- SPUtils.getInt(getActivity(), "firstNum");

				if (!list.isEmpty()) {
					// 非空,跳转到WebView界面和跟读详情界面
					Intent intent = null;
					if (TextUtils.isEmpty(type) || !type.equals("FOLLOWREAD")) {
						// 跳转到WebView界面
						intent = new Intent(getActivity(),
								GrammarThirdActivity.class);
					} else {
						
						if("1".equals(list.get(index).REPEAT_DONE)){
							intent = new Intent(getActivity(),
									AnswerListDetailsActivity.class);
							SPUtils.put(getActivity(), list.get(index).LESSON_ID+"0", true);
						}else{
							
							if(SPUtils.getBoolean(getActivity(), list.get(index).LESSON_ID+"0")){
								intent = new Intent(getActivity(),
										AnswerListDetailsActivity.class);
								
								
							}else{
								// 跳转到原生的跟读界面
								intent = new Intent(getActivity(),
										FollowReadDetailsActivity.class);
							}
						}
					}

					intent.putExtra("lESSON_ID", list.get(index).LESSON_ID);
					intent.putExtra("LESSON_NAME", list.get(index).LESSON_NAME);
					startActivity(intent);
				}
			}

//		}
	};
	private ArrayList<GrammarSecondListInfo> list = new ArrayList<GrammarSecondListInfo>();

	// 请求服务器返回的单元格
	private RequestCallBack<String> callBack = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			String json = responseInfo.result;

			Gson gson = new Gson();

			GrammarSecondResp grammarSecondResp = gson.fromJson(json,
					GrammarSecondResp.class);
			list.addAll(grammarSecondResp.LIST);

			int childCount = fwl.getChildCount();

			for (int i = 0; i < childCount; i++) {
				fwl.getChildAt(i).setOnClickListener(toastTagOcl);
			}
		}

		@Override
		public void onFailure(HttpException error, String msg) {

		}
	};

}
